package common.db.handlers;

import common.db.RowProcessor;
import common.db.ScalarProcessor;

import java.sql.ResultSet;
import java.sql.SQLException;


/**
 * Contains basic functionality for handlers for resultsets that return only one row.
 */
public abstract class OneRowHandler<E> implements ResultSetHandler<E>
{

	public final static ListHandler<Integer> INTEGER_HANDLER =
			ListHandler.getInstance(ScalarProcessor.getInstance(Integer.class));
	

	public E handle(ResultSet rs)
	{
		try
		{
			if (rs.next())
				return processRow(rs);
			else
				return null;
		}
		catch (SQLException e)
		{
			throw new RuntimeException(e);    // trebalo bi da signaliziramo nekom sql greskom
		}
	}

	public static <E> OneRowHandler<E> getInstance(final RowProcessor<E> rowProcessor)
	{
		return new OneRowHandler<E>()
		{

			protected E processRow(ResultSet rs) throws SQLException
			{
				return rowProcessor.processRow(rs);
			}
		};
	}

	protected abstract E processRow(ResultSet rs) throws SQLException;

}
